package elitech.vietnam.weatherfashion.location;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.google.gson.Gson;

import elitech.vietnam.weatherfashion.config.Utils;

public class MyLocationService {

	public static MyLocationObject getLocation() {
		MyLocationObject result = null;

		final String urlString = "http://smart-ip.net/geoip-json?callback=getip";

		try {
			// Create a URL for the desired page
			URL url;
			url = new URL(urlString);

			// Read all the text returned by the server
			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream()));

			String jsonString = "";
			String line = null;
			while ((line = in.readLine()) != null) {
				jsonString = jsonString.concat(line);
			}
			in.close();

			jsonString = jsonString.substring("getip(".length(),
					jsonString.length() - ");".length());

			result = new Gson().fromJson(jsonString, MyLocationObject.class);

		} catch (Exception e) {
			e.printStackTrace();
			Utils.Log("MyLocationService-getLocation() error: " + e);
			result = null;
		}

		return result;
	}

	public static MyLocationObject2 getLocation2() {
		MyLocationObject2 result = null;
		//AppUtils.Log("Start getLocation2 ");
		try {

			final String urlString = "http://ip2country.sourceforge.net/ip2c.php?format=JSON";
			// Create a URL for the desired page
			URL url;
			url = new URL(urlString);

			// Read all the text returned by the server
			BufferedReader in = new BufferedReader(new InputStreamReader(
					url.openStream()));

			String jsonString = "";
			String line = null;
			while ((line = in.readLine()) != null) {
				jsonString = jsonString.concat(line);
			}
			in.close();
			result = new Gson().fromJson(jsonString, MyLocationObject2.class);
			//AppUtils.Log("Stop getLocation2: " + result);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			//AppUtils.Log("Loi getLocation2: " + e);
			return null;
		}

	}

}
